# servercontroller.py
from pysage import Actor, ActorManager
import util
from messages import *
import subprocess, ctypes
import logging
import os

omanager = ActorManager.get_singleton()

class ServerController(Actor):
    subscriptions = []
    def __init__(self):
        Actor.__init__(self)
        self.process = None
    def online(self):
        path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'main.py')
        if subprocess.mswindows:
            cmd = ('python.exe', path)
        else:
            cmd = ('/usr/bin/env', 'python2.5', path)
        logging.debug('servercontroller: running cmd "%s"' % str(cmd))
        self.process = subprocess.Popen(cmd)
        logging.debug('started process pid: %s' % self.process.pid)
    def offline(self):
        if subprocess.mswindows:
            ctypes.windll.kernel32.TerminateProcess(int(self.process._handle), -1)
            # os.popen('TASKKILL /PID '+str(self.process.pid)+' /F')
            self.process.wait()
            logging.debug('process.poll(): %s' % self.process.poll())
        else:
            subprocess.call(('kill', str(self.process.pid)))
        self.process = None


